/*
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.example.admob.lunarlander;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;

import com.admob.android.ads.AdListener;
import com.admob.android.ads.AdView;
import com.admob.android.ads.InterstitialAd;
import com.admob.android.ads.InterstitialAdListener;
import com.admob.android.ads.SimpleAdListener;
import com.admob.android.ads.InterstitialAd.Event;
import com.example.admob.lunarlander.LunarView.LunarThread;

/**
 * This is a simple LunarLander activity that houses a single LunarView. It
 * demonstrates...
 * <ul>
 * <li>animating by calling invalidate() from draw()
 * <li>loading and drawing resources
 * <li>handling onPause() in an animation
 * </ul>
 */
public class LunarLander extends Activity implements AdListener, InterstitialAdListener {
    private static final int MENU_EASY = 1;

    private static final int MENU_HARD = 2;

    private static final int MENU_MEDIUM = 3;

    private static final int MENU_PAUSE = 4;

    private static final int MENU_RESUME = 5;

    private static final int MENU_START = 6;

    private static final int MENU_STOP = 7;

    private SensorManager mSensorManager;
    
    /** A handle to the thread that's actually running the animation. */
    private LunarThread mLunarThread;

    /** A handle to the View in which the game is running. */
    private LunarView mLunarView;
    
    /** saved instance state */
    private Bundle mSavedInstanceState;
    
    
    /** AdMob Interstitial Ad */
    private InterstitialAd mInterstitialAd;
    
    /**
     * Invoked during init to give the Activity a chance to set up its Menu.
     * 
     * @param menu the Menu to which entries may be added
     * @return true
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(0, MENU_START, 0, R.string.menu_start);
        menu.add(0, MENU_STOP, 0, R.string.menu_stop);
        menu.add(0, MENU_PAUSE, 0, R.string.menu_pause);
        menu.add(0, MENU_RESUME, 0, R.string.menu_resume);
        menu.add(0, MENU_EASY, 0, R.string.menu_easy);
        menu.add(0, MENU_MEDIUM, 0, R.string.menu_medium);
        menu.add(0, MENU_HARD, 0, R.string.menu_hard);

        return true;
    }

    /**
     * Invoked when the user selects an item from the Menu.
     * 
     * @param item the Menu entry which was selected
     * @return true if the Menu item was legit (and we consumed it), false
     *         otherwise
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_START:
                mLunarThread.doStart();
                return true;
            case MENU_STOP:
                mLunarThread.setState(LunarThread.STATE_LOSE,
                        getText(R.string.message_stopped));
                return true;
            case MENU_PAUSE:
                mLunarThread.pause();
                return true;
            case MENU_RESUME:
                mLunarThread.unpause();
                return true;
            case MENU_EASY:
                mLunarThread.setDifficulty(LunarThread.DIFFICULTY_EASY);
                return true;
            case MENU_MEDIUM:
                mLunarThread.setDifficulty(LunarThread.DIFFICULTY_MEDIUM);
                return true;
            case MENU_HARD:
                mLunarThread.setDifficulty(LunarThread.DIFFICULTY_HARD);
                return true;
        }

        return false;
    }

    /**
     * Invoked when the Activity is created.
     * 
     * @param savedInstanceState a Bundle containing state saved from a previous
     *        execution, or null if this is a new execution
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // store state for lunar lander if needed
        mSavedInstanceState = savedInstanceState;
        
        // turn off the window's title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // tell system to use the layout defined in our XML file
        setContentView(R.layout.splash);
        
//        AdManager.setTestDevices(new String[] { AdManager.TEST_EMULATOR, "D81E0EFAB674357C2895265D9C5C13D5" });        
//        AdManager.setTestAction("video_int");
        // call for an Interstitial Ad
        mInterstitialAd = new InterstitialAd(Event.APP_START, this);
        mInterstitialAd.requestAd(this);
    }

    
    
    /**
     * If we fail to receive an interstitial ad, we just keep going on with
     * our application loading and execution.
     */
    @Override
    public void onFailedToReceiveInterstitial(InterstitialAd interstitialAd) {
      // we couldn't get an interstitial ad before the game. Load the game.
      if (interstitialAd == mInterstitialAd) {
        switchToLunarView();
      }
    }

    /**
     * If we get an interstitial ad successfully, we can show the ad. 
     */
    @Override
    public void onReceiveInterstitial(InterstitialAd interstitialAd) {
      if(interstitialAd == mInterstitialAd) {
        mInterstitialAd.show(this);
      }
    }

    
    
    /**
     * After the ad has been shown, it will return with an activity result where
     * ADMOB_INTENT_BOOLEAN is true.  Once you receive this result you can continue
     * application loading and execution.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if(data != null && data.getBooleanExtra(InterstitialAd.ADMOB_INTENT_BOOLEAN, false)) {
        switchToLunarView();
      }
      super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Switches to the Lunar Lander view, to be called when showing the splash screen.
     */
    
  private void switchToLunarView() {
    setContentView(R.layout.lunar_layout);

    // Lunar Lander initialization starts here

    // Use the phone's orientation to control the rocket ship.
    mSensorManager = (SensorManager) getSystemService( SENSOR_SERVICE );
    
    // get handles to the LunarView from XML, and its LunarThread
    mLunarView = (LunarView) findViewById(R.id.lunar);
    mLunarThread = mLunarView.getThread();

    // give the LunarView a handle to the TextView used for messages
    TextView text = (TextView) findViewById(R.id.text);
    AdView ad = (AdView) findViewById(R.id.ad);
    ad.setAdListener(new LunarLanderListener());
    InterstitialAd interstitial = new InterstitialAd(Event.SCREEN_CHANGE, this);
    interstitial.requestAd(this); //request an ad now so it's ready when we want to show it
    mLunarView.setTextView(text, ad, interstitial);

    if (mSavedInstanceState == null) {
      // we were just launched: set up a new game
      mLunarThread.setState(LunarThread.STATE_READY);
      Log.w(this.getClass().getName(), "SIS is null");
    } else {
      // we are being restored: resume a previous game
      mLunarThread.restoreState(mSavedInstanceState);
      Log.w(this.getClass().getName(), "SIS is nonnull");
    }
  }    
    
    
    private class LunarLanderListener extends SimpleAdListener
    {

		/* (non-Javadoc)
		 * @see com.admob.android.ads.AdView.SimpleAdListener#onFailedToReceiveAd(com.admob.android.ads.AdView)
		 */
		@Override
		public void onFailedToReceiveAd(AdView adView)
		{
			// TODO Auto-generated method stub
			super.onFailedToReceiveAd(adView);
		}

		/* (non-Javadoc)
		 * @see com.admob.android.ads.AdView.SimpleAdListener#onFailedToReceiveRefreshedAd(com.admob.android.ads.AdView)
		 */
		@Override
		public void onFailedToReceiveRefreshedAd(AdView adView)
		{
			// TODO Auto-generated method stub
			super.onFailedToReceiveRefreshedAd(adView);
		}

		/* (non-Javadoc)
		 * @see com.admob.android.ads.AdView.SimpleAdListener#onReceiveAd(com.admob.android.ads.AdView)
		 */
		@Override
		public void onReceiveAd(AdView adView)
		{
			// TODO Auto-generated method stub
			super.onReceiveAd(adView);
		}

		/* (non-Javadoc)
		 * @see com.admob.android.ads.AdView.SimpleAdListener#onReceiveRefreshedAd(com.admob.android.ads.AdView)
		 */
		@Override
		public void onReceiveRefreshedAd(AdView adView)
		{
			// TODO Auto-generated method stub
			super.onReceiveRefreshedAd(adView);
		}
    	
    }

    /* (non-Javadoc)
	 * @see com.admob.android.ads.AdView.AdListener#onFailedToReceiveAd(com.admob.android.ads.AdView)
	 */
	public void onFailedToReceiveAd(AdView adView)
	{
		Log.d("Lunar", "onFailedToReceiveAd");
	}

	/* (non-Javadoc)
	 * @see com.admob.android.ads.AdView.AdListener#onFailedToReceiveRefreshedAd(com.admob.android.ads.AdView)
	 */
	public void onFailedToReceiveRefreshedAd(AdView adView)
	{
		Log.d("Lunar", "onFailedToReceiveRefreshedAd");
	}

	/* (non-Javadoc)
	 * @see com.admob.android.ads.AdView.AdListener#onReceiveAd(com.admob.android.ads.AdView)
	 */
	public void onReceiveAd(AdView adView)
	{
		Log.d("Lunar", "onReceiveAd");
	}

	/* (non-Javadoc)
	 * @see com.admob.android.ads.AdView.AdListener#onReceiveRefreshedAd(com.admob.android.ads.AdView)
	 */
	public void onReceiveRefreshedAd(AdView adView)
	{
		Log.d("Lunar", "onReceiveRefreshedAd");
	}

	/**
     * Invoked when the Activity loses user focus.
     */
    @Override
    protected void onPause() {
        super.onPause();
        if(mSensorManager != null && mLunarView != null) {
          mSensorManager.unregisterListener( mLunarView );
          mLunarView.getThread().pause(); // pause game when Activity pauses
        }
    }
    
    /**
     * Invoked when the Activity gains focus.
     */
    @Override
    protected void onResume() {
        super.onResume();
        if(mSensorManager != null) {
          List<Sensor> sensors = mSensorManager.getSensorList( Sensor.TYPE_ORIENTATION );
          if (sensors.size() > 0)
          {
  	        Sensor orientation = sensors.get( 0 );
  	        mSensorManager.registerListener( 
  	        		mLunarView, 
  	                orientation,
  	                SensorManager.SENSOR_DELAY_FASTEST);
          }
        }
    }

    /**
     * Notification that something is about to happen, to give the Activity a
     * chance to save state.
     * 
     * @param outState a Bundle into which this Activity should save its state
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // just have the View's thread save its state into our Bundle
        super.onSaveInstanceState(outState);
        if(mLunarThread != null) {
          mLunarThread.saveState(outState);
          Log.w(this.getClass().getName(), "SIS called");
        }
    }
}
